import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Toast } from 'vant'
import Vue from 'vue'
const request = axios.create({
  // baseURL: 'http://toutiao.itheima.net/'
  baseURL: 'http://127.0.0.1:5000/'
})

Vue.prototype.$axios = axios
// 添加请求拦截器
request.interceptors.request.use(
  function (config) {
    // console.log("请求拦截器中的token", store.state.tokenObj)
    // 在发送请求之前做些什么
    if (store.state.tokenObj) {
      config.headers.Authorization = store.state.tokenObj
    }
    return config
  },
  async function (error) {
    // 对请求错误做些什么
    // return Promise.reject(error)
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response
  },
  async function (error) {
    // 对响应错误做点什么
    try {
      if (error.response.status === 401) {
        const res = await axios({
          url: 'http://toutiao.itheima.net/v1_0/authorizations',
          // url: 'http://127.0.0.1:5000/v1_0/authorizations',
          method: 'put',
          headers: {
            // Authorization: 'Bearer ' + store.state.tokenObj.refresh_token
            Authorization: store.state.tokenObj.refresh_token
          }
        })
        console.log('res', res)
        store.commit('changeTokenObj', {
          token: res.data.data.token,
          refresh_token: store.state.tokenObj.refresh_token
        })
        return request(error.config)
      }
    } catch {
      Toast.fail('登陆状态失效，请重新登陆')
      router.push('/login')
    }
  }
)

export default request
